package fu.k4c.vTeam.Manage;

import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.gson.Gson;

import fu.k4c.vTeam.R;
import fu.k4c.vTeam.HomeActivity;
import fu.k4c.vTeam.Controller.VlocationItemizedOverlay;
import fu.k4c.vTeam.Login.ChangePasswordActivity;
import fu.k4c.vTeam.Login.LoginActivity;
import fu.k4c.vTeam.Main.ViewManagerActivity;
import fu.k4c.vTeam.Object.AccentRemover;
import fu.k4c.vTeam.Object.Account;
import fu.k4c.vTeam.Object.CreateLocationStatus;

public class EditPlaceActivity extends MapActivity {
	MapView mMapview;
	VlocationItemizedOverlay mMyOverlay;
	LocationManager mLocationManager;
	LocationListener mLocationListener;
	String city = "";
	ProgressDialog proDialog;
	String category = "";
	String categoryName = "";
	String email = "";
	String idPlace;
	int slat;
	int slong;
	int i = 0;
	GeoPoint gp = new GeoPoint(21032757, 105849667);
	GeoPoint gp2 = new GeoPoint(21032757, 105849667);
	GeoPoint gp3 = new GeoPoint(10830608, 106631927);
	/** Called when the activity is first created. */
	String cities[] = { "Khác", "Hà Nội", "TP Hồ Chí Minh" };
	String categories[] = { "Ẩm Thực", "Bệnh Viện", "Cà Phê", "Mua Sắm",
			"Trạm Xăng", "Giải Trí", "ATM" };
	Bundle data;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit_place_activity);
		overridePendingTransition(android.R.anim.fade_in,
				android.R.anim.fade_out);
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);
		data = getIntent().getExtras();
		final EditText et_address = (EditText) findViewById(R.id.et_edit_place_activity_address);
		final EditText et_place_name = (EditText) findViewById(R.id.et_edit_place_activity_name);
		final EditText et_phone_number = (EditText) findViewById(R.id.et_edit_place_activity_phone);
		final EditText et_detail = (EditText) findViewById(R.id.et_edit_place_activity_place_detail);

		if (data != null) {
			email = data.getString("username");
			idPlace = data.getString("IDofItemRevision");
			et_address.setText(data.getString("address"));
			et_place_name.setText(data.getString("placename"));
			et_phone_number.setText(data.getString("placetel"));
			et_detail.setText(data.getString("des"));
			// Toast.makeText(getApplicationContext(),
			// data.getString("lat")+","+data.getString("long"),Toast.LENGTH_LONG).show();
			Double mlat = Double.parseDouble(data.getString("lat"));
			Double mlong = Double.parseDouble(data.getString("long"));
			slat = (int) (mlat * 1000000);
			slong = (int) (mlong * 1000000);
		}
		Spinner Cityspinner = (Spinner) findViewById(R.id.sp_edit_place_activity_provide);
		ArrayAdapter<String> spinnerArrayAdapter1 = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_item, cities);
		spinnerArrayAdapter1
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		Cityspinner.setAdapter(spinnerArrayAdapter1);
		if (data.getString("cityID").equals("1")) {
			Cityspinner.setSelection(getIndex(Cityspinner, "Hà Nội"));
		} else if (data.getString("cityID").equals("2")) {
			Cityspinner.setSelection(getIndex(Cityspinner, "TP Hồ Chí Minh"));
		} else {
			Cityspinner.setSelection(getIndex(Cityspinner, "Khác"));
		}
		mMapview = (MapView) findViewById(R.id.map_edit_place_activity);
		mMapview.getController().setZoom(14);
		mMapview.setSatellite(false);
		GeoPoint p = new GeoPoint(slat, slong);
		gp = p;
		mMapview.getController().animateTo(p);
		mMyOverlay = new VlocationItemizedOverlay(this.getResources()
				.getDrawable(R.drawable.point));
		OverlayItem newplace = new OverlayItem(p, "New Place", "New Location");
		mMyOverlay.addOverlay(newplace);
		mMapview.getOverlays().add(mMyOverlay);
		mMapview.invalidate();
		mMapview.getOverlays().add(new Overlay() {
			@Override
			public boolean onTap(GeoPoint p, MapView arg1) {
				// TODO Auto-generated method stub
				mMyOverlay.clear();
				mMapview.invalidate();
				mMapview.getController().animateTo(p);
				gp = p;
				i++;
				OverlayItem newplace = new OverlayItem(p, "New Place",
						"New Location");
				mMyOverlay.addOverlay(newplace);
				mMapview.invalidate();
				return super.onTap(p, arg1);
			}
		});
		mMapview.setOnTouchListener(new OnTouchListener() {

			public boolean onTouch(View v, MotionEvent ev) {
				// TODO Auto-generated method stub
				switch (ev.getAction()) {
				case MotionEvent.ACTION_DOWN:
					mMapview.requestDisallowInterceptTouchEvent(true);
					break;
				case MotionEvent.ACTION_UP:
					mMapview.requestDisallowInterceptTouchEvent(false);
					break;
				}
				return false;
			}
		});

		// Cityspinner.setSelection(getIndex(Cityspinner,
		// data.getString("Categories")));
		Cityspinner
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						Object item = parent.getItemAtPosition(pos);
						city = item.toString();
						if (city.equals("Hà Nội")) {
							if (i > 0) {
								mMyOverlay.clear();
								mMapview.invalidate();
								mMapview.getController().setZoom(14);
								GeoPoint p1 = new GeoPoint(21032757, 105849667);
								mMapview.getController().animateTo(p1);
								OverlayItem newplace = new OverlayItem(p1,
										"New Place1", "New Location1");
								mMyOverlay.addOverlay(newplace);
								mMapview.invalidate();
							}

						} else if (city.equals("TP Hồ Chí Minh")) {
							if (i > 0) {
								mMyOverlay.clear();
								mMapview.invalidate();
								mMapview.getController().setZoom(14);
								GeoPoint p2 = new GeoPoint(10830608, 106631927);
								mMapview.getController().animateTo(p2);
								OverlayItem newplace = new OverlayItem(p2,
										"New Place2", "New Location2");
								mMyOverlay.addOverlay(newplace);
								mMapview.invalidate();
							}
						}

					}

					public void onNothingSelected(AdapterView<?> parent) {
					}
				});
		Spinner Categoryspinner = (Spinner) findViewById(R.id.sp_edit_place_activity_place_group);
		ArrayAdapter<String> spinnerArrayAdapter2 = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_item, categories);
		spinnerArrayAdapter2
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The
																							// drop
																							// down
																							// vieww
		Categoryspinner.setAdapter(spinnerArrayAdapter2);
		Categoryspinner.setSelection(getIndex(Categoryspinner,
				data.getString("Categories")));
		Categoryspinner
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						Object item = parent.getItemAtPosition(pos);
						category = item.toString();
					}

					public void onNothingSelected(AdapterView<?> parent) {
					}
				});
		Button btn_back = (Button) findViewById(R.id.btn_edit_place_activity_back);
		btn_back.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		Button btn_delete = (Button) findViewById(R.id.btn_edit_place_activity_delete);
		btn_delete.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				new AlertDialog.Builder(EditPlaceActivity.this)
						.setMessage("Bạn muốn xóa địa điểm này?")
						.setPositiveButton("Có",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {

										try {
											proDialog = ProgressDialog
													.show(EditPlaceActivity.this,
															"",
															"Đang kết nối đến máy chủ...");
											new Thread() {
												public void run() {

													try {
														sleep(1000);

													} catch (Exception e) {
														System.out.print(e
																.toString());
													}
													// dismiss the
													// progressdialog
													proDialog.dismiss();
												}
											}.start();
											SchemeRegistry registry = new SchemeRegistry();
											registry.register(new Scheme(
													"http",
													PlainSocketFactory
															.getSocketFactory(),
													80));
											HttpParams httpParams = new BasicHttpParams();
											ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
													httpParams, registry);
											HttpClient client = new DefaultHttpClient(
													connMgr, httpParams);
											HttpPost post = new HttpPost(
													getString(R.string.connectionString)
															+ "vLocationService/deleteitem");
											post.setHeader("Accept",
													"application/json");
											post.setHeader("Content-type",
													"application/json");
											HashMap<String, Object> postParameters = new HashMap<String, Object>();
											postParameters.put("ItemID",
													idPlace);
											Gson gson = new Gson();
											String jsonParameters = gson
													.toJson(postParameters);
											post.setEntity(new StringEntity(
													jsonParameters));
											HttpResponse response = client
													.execute(post);
											HttpEntity entity = response
													.getEntity();
											String jsonresult = EntityUtils
													.toString(entity);
											Account acc = gson.fromJson(
													jsonresult, Account.class);
											if (acc.getStatus().equals("false")) {
												Toast.makeText(
														getApplicationContext(),
														"Không xóa được địa điểm này",
														Toast.LENGTH_LONG)
														.show();
											} else {
												Toast.makeText(
														getApplicationContext(),
														"Xóa địa điểm thành công",
														Toast.LENGTH_LONG)
														.show();
												Intent i = new Intent(
														EditPlaceActivity.this,
														ViewManagerActivity.class);
												i.putExtra("email", email);
												setResult(RESULT_OK, i);
												finish();
											}
										} catch (Exception e) {
											// TODO: handle exception
										}
									}
								})
						.setNegativeButton("Không",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
									}
								}).create().show();

			}
		});
		Button btn_submit = (Button) findViewById(R.id.btn_edit_place_activity_save);
		btn_submit.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				String mCity = city;

				String mAddress = et_address.getText().toString();

				String mPlaceName = et_place_name.getText().toString();
				String mCategory = category;

				String mPhone = et_phone_number.getText().toString();

				String mDetail = et_detail.getText().toString();
				if (mAddress.equals("")) {
					Toast.makeText(getApplicationContext(),
							"Bạn phải nhập địa chỉ", Toast.LENGTH_LONG).show();
				} else if (mPlaceName.equals("")) {
					Toast.makeText(getApplicationContext(),
							"Bạn phải nhập tên địa điểm", Toast.LENGTH_LONG)
							.show();
				} else if (gp.equals(gp2) || gp.equals(gp3)) {
					Toast.makeText(getApplicationContext(),
							"Bạn phải chọn địa điểm trên bản đồ",
							Toast.LENGTH_LONG).show();
				} else {
					if (mCity.equals("Hà Nội")) {
						mCity = "1";

					} else if (mCity.equals("TP Hồ Chí Minh")) {
						mCity = "2";
					} else if (mCity.equals("Khác")) {
						mCity = "3";
					}
					if (mCategory.equals("Ẩm Thực")) {
						mCategory = "197";
						categoryName = "amthuc";

					} else if (mCategory.equals("Bệnh Viện")) {
						mCategory = "198";
						categoryName = "benhvien";
					} else if (mCategory.equals("Cà Phê")) {
						mCategory = "199";
						categoryName = "cafe";
					} else if (mCategory.equals("Mua Sắm")) {
						mCategory = "200";
						categoryName = "shopping";
					} else if (mCategory.equals("Trạm Xăng")) {
						mCategory = "201";
						categoryName = "tramxang";
					} else if (mCategory.equals("Giải Trí")) {
						mCategory = "203";
						categoryName = "giaitri";
					} else if (mCategory.equals("ATM")) {
						mCategory = "202";
						categoryName = "atm";
					}
					try {
						SchemeRegistry registry = new SchemeRegistry();
						registry.register(new Scheme("http", PlainSocketFactory
								.getSocketFactory(), 80));
						HttpParams httpParams = new BasicHttpParams();
						ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
								httpParams, registry);
						HttpClient client = new DefaultHttpClient(connMgr,
								httpParams);
						HttpPost post = new HttpPost(
								getString(R.string.connectionString)
										+ "vLocationService/updatebyuser");
						post.setHeader("Accept", "application/json");
						post.setHeader("Content-type", "application/json");
						HashMap<String, Object> postParameters = new HashMap<String, Object>();
						postParameters.put("citiID", mCity);
						postParameters.put("address", mAddress);
						postParameters.put("placename", mPlaceName);
						postParameters.put("categoryID", mCategory);
						postParameters.put("phone", mPhone);
						postParameters.put("longitude",
								"" + gp.getLongitudeE6() / 1E6);
						postParameters.put("latitude", "" + gp.getLatitudeE6()
								/ 1E6);
						postParameters.put("email", email);
						AccentRemover aremover = new AccentRemover();
						String mnamesearch = aremover.removeAccent(mPlaceName)
								.replace(" ", "");
						String mnameurl = aremover.removeAccent(mPlaceName)
								.replace(" ", "-");
						postParameters.put("nameurl", mnameurl);
						postParameters.put("namesearch", mnamesearch);
						postParameters.put("Descriptiontextcs", mDetail);
						postParameters.put("placeID", idPlace);
						Gson gson = new Gson();
						String jsonParameters = gson.toJson(postParameters);
						post.setEntity(new StringEntity(jsonParameters, "UTF-8"));
						HttpResponse response = client.execute(post);
						HttpEntity entity = response.getEntity();
						String jsonresult = EntityUtils.toString(entity);
						Account acc = gson.fromJson(jsonresult, Account.class);
						if (acc.getStatus().equals("false")) {
							Toast.makeText(getApplicationContext(),
									"Cập nhật thông tin lỗi", Toast.LENGTH_LONG)
									.show();
						} else {
							Toast.makeText(getApplicationContext(),
									"Cập nhật thông tin Thành công",
									Toast.LENGTH_LONG).show();
							Intent i = new Intent(EditPlaceActivity.this,
									ViewManagerActivity.class);
							i.putExtra("email", email);
							setResult(RESULT_OK, i);
							finish();
						}

					} catch (Exception e) {
						// TODO: handle exception
						Toast.makeText(getApplicationContext(), e.toString(),
								Toast.LENGTH_LONG).show();
					}
				}
			}
		});
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	private int getIndex(Spinner spinner, String myString) {

		int index = 0;

		for (int i = 0; i < spinner.getCount(); i++) {
			if (spinner.getItemAtPosition(i).equals(myString)) {
				index = i;
			}
		}
		return index;
	}
}
